package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wit.witmg.entity.TMonitDust;
import com.wit.witmg.entity.TMonitElect;
import com.wit.witmg.mapper.TMonitElectMapper;
import com.wit.witmg.service.ITMonitElectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <p>
 * 电耗监测记录表（流程数据） 服务实现类
 * </p>
 *
 * @author bob
 * @since 2025-08-20
 */
@Service
public class TMonitElectServiceImpl extends ServiceImpl<TMonitElectMapper, TMonitElect> implements ITMonitElectService {

    @Override
    public Object add(HttpServletRequest request, String json) {
        TMonitElect t= JSON.parseObject(json,TMonitElect.class);
        if(t.getId()!=null && t.getId()>0){
            boolean bl=  updateById(t);
            if(!bl){
                return JsonResult.error(ErrorCode.ERR_504);
            }
        }else{
//            t.setDate(System.currentTimeMillis() / 1000);
            boolean bl= save(t);
            if(!bl){
                return JsonResult.error(ErrorCode.ERR_504);
            }
        }
        return JsonResult.success(t);
    }

    @Override
    public Object get(HttpServletRequest request, Long dt0, Long dt1, String sid, String bn) {
        //参数根据sid和bn（常空缺）筛选，若dt0和dt1都存在则返回date在两者之间的数据,否则返回最新的20条数据。
        LambdaQueryWrapper<TMonitElect> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(TMonitElect::getDate);
        if(sid != null && !sid.isEmpty()){
            qw.eq(TMonitElect::getSid, sid);
        }
        if(bn != null && !bn.isEmpty()){
            qw.eq(TMonitElect::getBn, bn);
        }
        if (dt0 != null && dt1 != null) {
            // 查询 date 在 dt0 和 dt1 之间的数据
            qw.between(TMonitElect::getDate, dt0, dt1);
        }else{
            qw.last("limit 20");
        }
        return JsonResult.success(list(qw));
    }

    @Override
    public Object del(HttpServletRequest request, Integer id) {
        if(id==null) {
            return JsonResult.error(ErrorCode.ERR_200);
        }
        boolean bl=removeById(id);
        if(bl){
            return JsonResult.success();
        }
        return JsonResult.error(ErrorCode.ERR_313);
    }
}
